import Axios from "@/api";

let userInfo: any = sessionStorage.getItem("userInfo");
userInfo = userInfo ? JSON.parse(userInfo) : null;
let loading = false;

const state = {
  // 当前登录用户信息
  currentUser: userInfo ? userInfo.user : {}
};

const mutations = {
  setUser(state: any, val: any) {
    if (val) {
      state.currentUser = val.user;
      // state.roles = val.roles;
      // state.permissions = val.permissions;
    } else {
      state.currentUser = {};
    }
  }
};

const actions = {
  setUser({ commit }: any, val = {}) {
    commit("setUser", val);
  },

  /**
   * 更新本地用户信息
   * @param commit
   * @param force {Bollean} 是否强制更新本地session用户信息
   */
  async updateUser({ commit }: any, force = false) {
    if (loading) return Promise.resolve();
    const userInfo: any = sessionStorage.getItem("userInfo");
    const token = localStorage.getItem("token");

    if (token && (!userInfo || force)) {
      loading = true;
      await Axios.GetUserInfo().then((res: any) => {
        if (res && res.code === 200) {
          const _data = { user: res.user, permissions: res.permissions, roles: res.roles };
          commit("setUser", _data);
          sessionStorage.setItem("userInfo", JSON.stringify(_data));
        }
      });
      loading = false;
    }
    return Promise.resolve();
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
